package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	for {
		buf := make([]byte, 1024)
		n, addr, err := conn.ReadFromUDP(buf)
		if err != nil {
			fmt.Println("read from " + addr.String() + "err:" + err.Error())
			continue
		}
		if n <= 0 {
			continue
		}
		switch buf[0] {
		case 0:
			// c
			if !rd.SetNX(context.Background(), string(buf[1:]), addr.String(), time.Minute << 2).Val() {
				conn.WriteToUDP([]byte("err"), addr)
				break
			}
			if !rd.SetNX(context.Background(), addr.String(), string(buf[1:]), time.Minute << 2).Val() {
				rd.Del(context.Background(), string(buf[1:]))
				conn.WriteToUDP([]byte("err"), addr)
				break
			}

			conn.WriteToUDP([]byte("ok"), addr)
		case 1:
			// r
			res, err := rd.Get(context.Background(), string(buf[1:])).Result()
			if err != nil {
				conn.WriteToUDP([]byte{}, addr)
				break
			}
			conn.WriteToUDP([]byte(res), addr)
		}
	}
}